﻿using System;
using System.Collections.Generic;
using System.Text;
using rkShared;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using rkShared.Net;
using rkShared.BEncode;
using System.IO;
using rkShared.Serialization;

namespace TestApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientInfo _ci = new ClientInfo();
            _ci.ClientID = Guid.NewGuid();
            _ci.ColorPreference = new Vector3(0.5f, 0.2f, 0.3f);
            _ci.IPAddress = "127.0.0.1";
            _ci.NickName = "saviour";
            _ci.Port = 50005;
            
            NetMessage _msg = new NetMessage();
            _msg.ClientID = _ci.ClientID;
            _msg.Data = _ci;
            _msg.MessageType = MessageType.Dead;

            byte[] _bencoded = GetBEncodedBytes(_msg);
            byte[] _systemBytes = GetSystemSerializedBytes(_msg);

            _msg = DeserializeBEncodedBytes(_bencoded);
        }

        private static NetMessage DeserializeBEncodedBytes(byte[] bencoded)
        {
            BEncodedDictionary _dict = new BEncodedDictionary();
            _dict.Decode(bencoded);

            NetMessage _result = new NetMessage();
            _result.DeserializeFromDictionary(_dict);
            return _result;
        }
        /// <summary>
        /// serializes ClientInfo object using BEncoded rules.
        /// </summary>
        /// <param name="ci"></param>
        /// <returns></returns>
        private static byte[] GetBEncodedBytes(IBinarySerializable element)
        {
            BEncodedDictionary _dict = new BEncodedDictionary();
            element.SerializeToDictionary(_dict);

            MemoryStream _ms = new MemoryStream();
            BinaryWriter _writer = new BinaryWriter(_ms);

            _dict.Encode(_writer);

            byte[] _result = _ms.ToArray();
            _ms.Close();
            return _result;
        }
        /// <summary>
        /// Serializes the ClientInfo object using .NET's ISerializable mechanism
        /// </summary>
        /// <param name="ci"></param>
        /// <returns></returns>
        private static byte[] GetSystemSerializedBytes(NetMessage msg)
        {
            BinaryFormatter _formatter = new BinaryFormatter();
            MemoryStream _ms = new MemoryStream();
            _formatter.Serialize(_ms, msg);

            byte[] _result = _ms.ToArray();
            _ms.Close();
            return _result;
        }
    }
}
